
import json
import os
import time

import aip
import jsonpath
import pygame
import pyttsx3
import requests

# 百度自然语言处理接口密钥
nip_date = {
    'AppID' : '15573315',
    'API_Key' : 'GN84DYHpvzVma1zAfGvl7OT9',
    'Secret_Key' : 'kx61VvTX69apNq7GL5fdyw3d5hSYIr1G',
}

# 百度语音合成接口密钥
speech_date = {
    'AppID' : '15573145',

    'API_Key' : 'yFWcqoGOOQEQgt2Z6j5fQPPV',

    'Secret_Key' : '2s44IAhfbu4ppBlznN58PTtpe1x3A6ow',

}

# 对你的称呼
CALL = 'master'

# 运行根目录
root_path = r'E:\\Python37\\PYprogram\\'

# 播放音乐函数
def playmp3(file):

    pygame.mixer.init()
    # print("播放音乐1")
    track = pygame.mixer.music.load(root_path + file)
    pygame.mixer.music.play()
    time.sleep(30)
    pygame.mixer.music.stop()


# 获取城市代码
def get_city_code(city_name):
    with open(root_path + '_city.json','rb') as fp:
        city_date = json.load(fp)
    # print(city_date)
    json_path = '$.[?(@.city_name=="{}")].city_code'.format(city_name)
    # print(json_path)
    city_code = jsonpath.jsonpath(city_date,json_path)
    return city_code[0]

# 核心逻辑
def main():
    # 获取天气接口
    get_url = 'http://t.weather.sojson.com/api/weather/city/'

    # 初始化自然语言接口
    addr = aip.AipNlp(appId = nip_date['AppID'], apiKey= nip_date['API_Key'], secretKey= nip_date['Secret_Key'] )

    # ip183获取本机地理位置并提取
    addr_url = 'http://2019.ip138.com/ic.asp'
    response = requests.get(url = addr_url)
    response.encoding = 'gbk'
    # print(response.text)
    stext = response.text[response.text.find('来自：')+3:response.text.find('</center>')]
    # print(stext)

    # 自然语言处理得到确定城市
    result = addr.lexer(stext)
    result = jsonpath.jsonpath(result,'$..items[?(@.ne=="LOC")][basic_words][0]')
    # print(result[-1])
    # city_name = '河池'
    city_name = result[-1]

    # 得到城市代码
    city_code = get_city_code(city_name)

    # 调用天气接口
    get_url += str(city_code)
    response = requests.get(url = get_url)
    response.encoding = 'utf-8'
    # print(response.url)

    # 处理返回的接口信息
    weather_date = json.loads(response.text)
    shidu = jsonpath.jsonpath(weather_date,'$..shidu')  
    pm25 = jsonpath.jsonpath(weather_date,'$..pm25')  
    data = jsonpath.jsonpath(weather_date,'$..forecast[0].[high,low,ymd,week,type,notice]')
    # print(shidu,pm25,data)
    hour = eval(time.strftime('%H'))
    if 6 <= hour <= 9:
        hour = '早上'
    elif 13 <= hour <=17:
        hour = '下午'
    elif 18 <= hour <=23 or 0 <= hour <= 5:
        hour = '晚上'
    elif 10 <= hour <= 12:
        hour = '上午'
    
    
    # 生成朗读文本
    s = '{}，{}好,您现在{},今天是{}，{},空气湿度{}，pm2.5为{}，气温{}~{}，天气{}，{}'\
        .format(CALL,hour,city_name,data[2],data[3],shidu[0],pm25[0],data[1][2:],data[0][2:],data[-2],data[-1])
    # 初始化语音合成接口
    speech = aip.AipSpeech(appId = speech_date['AppID'], apiKey = speech_date['API_Key'], secretKey = speech_date['Secret_Key'])
    # 提交参数
    # vol音量
    # per风格
    # spd语速
    # pit语调
    options = {
        'vol':10,
        'per':0,
         'spd':3,
        # 'pit':9,
    }
    result = speech.synthesis(text = s,lang='zh',ctp = 1, options = options)

    # 成功返回二进制mp3,失败返回错误信息字典
    if not isinstance(result, dict):
        with open(root_path + 'auido.mp3', 'wb') as f:
            f.write(result)
        playmp3('auido.mp3')
    else:
        print(result)
if __name__ == "__main__":
    main()
